package com.glela.controller;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.cache.redis.RedisUtil;
import com.glela.constant.SmsConstant;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.request.RequestVerifyCodeModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.CheckCodeService;
import com.glela.platform.service.SmsService;
import com.glela.platform.service.UserService;

@Controller
@RequestMapping(value = "/common")
public class CommonController
{
	private static Logger logger = LoggerFactory.getLogger(InformationCheckController.class);

	@Resource
	private CheckCodeService checkCodeService;
	@Resource
	private UserService userService;
	
	@Resource
	RedisUtil redisUtil;
	
	@Resource
	private SmsService smsService;
	
	/**
	 * 发送验证码
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/sendVerifyCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> sendVerifyCode(@RequestBody RequestVerifyCodeModel model)
	{
		try {
			String mobile=model.getPhone();
			Integer type = model.getType();
			if(type == null){
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			Integer sendMode = SmsConstant.MODE_TEXT;
						
			if (type == SmsConstant.TYPE_REGISTER) {//注册
				ResponseUser user = userService.getUserByName(mobile);
				if (user != null) {
					return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20108), HttpStatus.OK); 
				}
			}else if(type == SmsConstant.TYPE_RESETPWD){//找回密码
				ResponseUser user = userService.getUserByName(mobile);
				if (user == null) {
					return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK); 
				}
			}
						
			boolean res = smsService.sendVerifyCodeSms(mobile, type, sendMode);
			if(res){
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20112), HttpStatus.OK); 			
		}catch (Exception e) {
			logger.error("发送验证码异常:" , e);
		}
		return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
	}
	
}

